package jmf;

import java.net.Socket;
import java.net.ServerSocket;
import java.io.OutputStream;
import java.io.FileInputStream;
import jmf.network.ProtocolConstants;

public class MediaAppServer {
  private static final String mediaFilename =
    "C:\\GiulianoXT\\Temp\\movie2.mpg";

  public static void main(String[] args) throws Exception {
    Socket sock = null;
    FileInputStream input = null;
    ServerSocket serverSock = new ServerSocket(
      ProtocolConstants.SERVER_PORT
    );

    int n;
    byte[] buffer = new byte[ProtocolConstants.SERVER_BUFFER_SZ];

    while (true) {
      try {
        System.out.println("Waiting connection...");
        sock = serverSock.accept();
        OutputStream out = sock.getOutputStream();

        System.out.println("Opening file...");
        input = new FileInputStream(mediaFilename);

        System.out.println("Sending file...");

        int count = 0;

        while ((n = input.read(buffer)) != -1) {
          count += n;
          out.write(buffer, 0, n);
          System.out.println(count/1024 + " kb");
        }

        System.out.println("File sent.\n");
      } catch (Exception e) {
        System.out.println(e.getMessage());
      } finally {
        sock.close();
        input.close();
      }
    }
  }
}
